<?php
namespace Home\Controller;
/**
 * Created by PhpStorm.
 * User: yhg97p
 * Date: 2016/4/6
 * Time: 21:14
 */
class PayController extends \Think\Controller {
    /**
     * 支付回调接口
     */
    public function nineteenPay(){
        $data = array();
        $data['info'] = json_encode($_POST);
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['ip'] = $_SERVER['REMOTE_ADDR'];
        $callback = M("CallbackParam")->add($data);
        $errorno = $_POST['error_code'];
        $orderSno = $_POST['order_id'];
        $Invest = M("Invest");
        $InvestInfo = $Invest->where(array("order_no"=>$orderSno))->find();
        if($InvestInfo && $errorno=='00000'){
            $Invest->where(array('order_no' => $orderSno))->save(array('paysuccess'=>'1'));
        }else{
            $Invest->where(array('order_no' => $orderSno))->save(array('paysuccess'=>'2'));
        }
    }
    /**
     * 支付查询接口
     */
    public function paymentConfirm(){
        $param = I('params');
        $userId =  $this->user['userId'];
        $bank_code = $param['bank_code'];
        $order_no = $param['order_no'];
        if(empty($bank_code)||empty($order_no)) $this->ajaxReturn(array('error' => 1,'info'=>"参数不全"));
        //获取银行卡信息
        $bankVerification = M("BankVerification")->where(array("bank_code"=>$bank_code))->find();
        $bank_code = $bankVerification['bank_code'];
        $card_holder = $bankVerification['card_holder'];
        $id_no = $bankVerification['id_no'];
        $mobile = $bankVerification['mobile'];
        $bankid = $bankVerification['id'];
        //获取订单信息
        $orderinfo = M("Invest")->where(array("order_no"=>$order_no))->find();
        $transAmount = intval($orderinfo['amount']);
        include_once(dirname(__FILE__).'/bankList.php');
        $info = $this->bankInfo($param['bank_code'],$bankList);
        $pcId = "";
        foreach($bankpcId as $key=>$val){
            if(strpos($info,$val)>=0){
                $pcId = $key;
            }
        }
        $transMap = array(
            "versionId" => "001",
            "businessType" => "1401",
            "insCode" => "",
            "merId"=>"",
            "orderId" => $order_no,
            "transDate" => date('YmdHis', time()),
            "transAmount" =>$transAmount,
            "cardByName" => base64_encode($card_holder),
            "cardByNo" =>$bank_code,
            "cardType" => "01",
            "bankCode" =>$pcId,
            "openBankName" => "",
            "cerType" => "01",
            "cerNumber" => $id_no,
            "mobile" => $mobile,
            "isAcceptYzm" => "01",
            "pageNotifyUrl" => "",
            "backNotifyUrl" => "",
            "orderDesc" => "",
            "dev" => "",
            "fee" => ""
        );
        $resBody = $this->mobaopay($transMap);//预支付
        $data = array();
        $data['order_no'] = $order_no;
        $data['bank_id'] = $bankid;
        $data['cardByName'] = $card_holder;
        $data['cardByNo'] = $bank_code;
        $data['bankCode'] = $pcId;
        $data['transAmount'] = $transAmount;
        $data['mobile'] = $mobile;
        $data['user_id'] = $userId;
        $data['status'] = 0;
        $result = M("Mobaopay")->add($data);
        
        if($resBody['refCode'] == "01"){//预支付成功 进行短信验证
            $res_sms = \Common\Util\Util::sms($mobile,$resBody['yzm']);
            $data = array();
            $data['yzm'] = $resBody['yzm'];
            $data['ksPayOrderId'] = $resBody['ksPayOrderId'];
            M("Mobaopay")->where(array("id"=>$result))->save($data);
            if($res_sms){
                $this->ajaxReturn(array('error' => 0,'info'=>array("msg"=>"短信发送成功","mobaoid"=>$result)));
            }else{
                $this->ajaxReturn(array('error' => 1,'info'=>"短信发送失败"));
            }
        }else{
            $this->ajaxReturn(array('error' => 1,'info'=>$resBody['refMsg']));
        }
    }
    //重新发送支付短信
    public function paysmsagain(){
        $param = I('params');
        $userId =  $this->user['userId'];
        $mobaoid = $param['mobaoid'];
        $Mobaopay = M("Mobaopay")->where(array("id"=>$mobaoid))->find();
        $res_sms = \Common\Util\Util::sms($Mobaopay['mobile'],$Mobaopay['yzm']);
        if($res_sms){
            $this->ajaxReturn(array('error' => 0,'info'=>"短信发送成功"));
        }else{
            $this->ajaxReturn(array('error' => 1,'info'=>"短信发送失败"));
        }
    }
    //支付短信验证
    public function paysmsverification(){
        $param = I('params');
        $userId =  $this->user['userId'];
        $yzm = $param['yzm'];
        $mobaoid = $param['mobaoid'];
        if(empty($mobaoid)||empty($yzm)) $this->ajaxReturn(array('error' => 1,'info'=>"参数不全"));
        $Mobaopay = M("Mobaopay")->where(array("id"=>$mobaoid,"yzm"=>$yzm))->find();

        if(empty($Mobaopay)) $this->ajaxReturn(array('error' => 1,'info'=>"查无数据"));
        $bankid = $Mobaopay['bank_id'];
        $bankVerification = M("BankVerification")->where(array("id"=>$bankid))->find();
        //贷记卡版本
        $transMap=array(
            "versionId"=>"001",  //版本号
            "businessType"=>"1411", //交易类型
            "insCode"=>"", //交易类型
            "merId"=>"",         //商户号
            "transDate"=>date('YmdHis',time()),//交易日期
            "transAmount"=>$Mobaopay['transamount'],
            "cardByName"=>base64_encode($Mobaopay['cardbyname']),
            "cardByNo"=>$Mobaopay['cardbyno'],  //卡号
            "cardType"=>"01",                  //卡类型
            "bankCode"=>$Mobaopay['bankcode'],                    //银行编号
            "openBankName"=>"",                //开户银行
            "cerType"=>"01",                     //证件类型
            "cerNumber"=>$bankVerification['id_no'],                   //证件号码
            "mobile"=>$Mobaopay['mobile'],           //手机号码
            "yzm"=>$yzm,                       //验证码     1401的返回验证码填入
            "ksPayOrderId"=>$Mobaopay['kspayorderid'],                //摩宝交易号  1401的返回的摩宝交易号填入
            "pageNotifyUrl"=>"",               //前台返回地址
            "backNotifyUrl"=>"",               //后台返回地址
            "orderDesc"=>"",                   //商品名称
            "dev"=>"",                         //自定义域
            "fee"=>"",                         //手续费
        );
        $resBody = $this->mobaopay($transMap);//直接支付
        if($resBody['refCode'] == "00"){//预支付成功 进行短信验证
            $data = array();
            $data['status'] = 1;
            M("Mobaopay")->where(array("id"=>$mobaoid))->save($data);
            //修改银行认证状态
            M("BankVerification")->where(array("id"=>$bankid))->save(array("status"=>2));
            M("Invest")->where(array("order_no"=>$Mobaopay['order_no']))->save(array("paysuccess"=>1));
            $this->ajaxReturn(array('error' => 0,'info'=>"支付成功"));
        }else{
            $this->ajaxReturn(array('error' => 1,'info'=>$resBody['refMsg']));
        }
    }
    public function bankInfo($card,$bankList)
    {
        $card_8 = substr($card, 0, 8);
        if (isset($bankList[$card_8])) {
            return $bankList[$card_8];
        }
        $card_6 = substr($card, 0, 6);
        if (isset($bankList[$card_6])) {
            return $bankList[$card_6];
        }
        $card_5 = substr($card, 0, 5);
        if (isset($bankList[$card_5])) {
            return $bankList[$card_5];
        }
        $card_4 = substr($card, 0, 4);
        if (isset($bankList[$card_4])) {
            return $bankList[$card_4];
        }
        return '该卡号信息暂未录入';
    }
    function curl_post($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    //预支付
    public function mobaopay($transMap)
    {
        require_once(dirname(dirname(dirname(__FILE__))).'/Notify/mobaopay/AESUtil.php');
        require_once(dirname(dirname(dirname(__FILE__))).'/Notify/mobaopay/HttpCilent.php');
        require_once(dirname(dirname(dirname(__FILE__))).'/Notify/mobaopay/EncodeUtil.php');
        //生产交易地址
        $url = "http://210.74.1.48:8080/ks_onlpay/gateways/trans";
        //$url="http://210.74.1.48:8080/ks_onlpay/gateways/trans";
        //商户号码(摩宝分配的商户号码,正式交易时候换成正式商户号码)
        $merId = "936320148160000";
        //商户密钥(摩宝分配的商户密钥,正式的交易的时候换成正式密钥)
        $merPubKey = "C324349C9F7C2F34";
        //贷记卡版本

        $transMap['merId'] = $merId;

        //获取URL格式字符串
        $EncodeUitl = new EncodeUitl();
        $transStr = $EncodeUitl->getUrlStr($transMap);

        //MD5加密
        $signData = strtoupper(md5($transStr . $merPubKey, false));
        $transMap["signType"] = "MD5";
        $transMap["signData"] = $signData;
        $transStr = $EncodeUitl->getUrlStr($transMap);

        //进行AES加密
        $aes = new AESUtil();
        // 加密  (参数一  明文报文   参数2 商户的私钥)
        $string = $aes->encrypt($transStr, $merPubKey);

        //发送交易
        $HttpCilnet = new HttpCilnet();
        $transData = array('merId' => $merId, 'transData' => $string);
        $resBody = $HttpCilnet->post2($url, $transData);
        $resBody = mb_convert_encoding($resBody, "utf-8", "GBK");
        $resBody = json_decode($resBody,true);
        return $resBody;
    }
}